#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
企业微信配置检查脚本
用于诊断企业微信API权限和配置问题
"""

import os
import sys
import requests
import json
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

def check_env_vars():
    """检查环境变量配置"""
    print("🔧 检查环境变量配置...")
    
    required_vars = {
        'WX_CORPID': '企业微信CorpID',
        'WX_CORPSECRET': '企业微信应用Secret（客服应用）',
        'WX_AGENT_SECRET': '企业微信应用Secret（内部消息应用）',
        'WX_AGENT_ID': '企业微信应用ID（内部消息应用）'
    }
    
    missing_vars = []
    for var, desc in required_vars.items():
        value = os.getenv(var)
        if not value:
            missing_vars.append(f"   ❌ {var} ({desc}) - 未配置")
        else:
            print(f"   ✅ {var} ({desc}) - 已配置")
    
    if missing_vars:
        print("\n❌ 缺少必要的环境变量:")
        for var in missing_vars:
            print(var)
        return False
    else:
        print("\n✅ 所有必要的环境变量已配置")
        return True

def test_access_token(corp_id, corp_secret, desc):
    """测试access_token获取"""
    print(f"\n🔑 测试获取access_token ({desc})...")
    
    try:
        url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
        params = {
            'corpid': corp_id,
            'corpsecret': corp_secret
        }
        
        print(f"   corp_id: {corp_id}")
        print(f"   corp_secret: {corp_secret[:6]}***（已隐藏）")
        
        response = requests.get(url, params=params, timeout=10)
        result = response.json()
        
        if result.get('errcode') == 0:
            access_token = result.get('access_token')
            print(f"   ✅ 获取access_token成功: {access_token[:20]}***")
            return access_token
        else:
            print(f"   ❌ 获取access_token失败: {result}")
            return None
            
    except Exception as e:
        print(f"   ❌ 获取access_token异常: {str(e)}")
        return None

def test_agent_list(access_token):
    """测试获取应用列表"""
    print(f"\n📋 测试获取应用列表...")
    
    try:
        url = "https://qyapi.weixin.qq.com/cgi-bin/agent/list"
        params = {'access_token': access_token}
        
        response = requests.get(url, params=params, timeout=10)
        result = response.json()
        
        if result.get('errcode') == 0:
            agent_list = result.get('agentlist', [])
            print(f"   ✅ 获取应用列表成功，共 {len(agent_list)} 个应用:")
            for agent in agent_list:
                print(f"      - agentid: {agent.get('agentid')}, name: {agent.get('name')}")
            return agent_list
        else:
            print(f"   ❌ 获取应用列表失败: {result}")
            return []
            
    except Exception as e:
        print(f"   ❌ 获取应用列表异常: {str(e)}")
        return []

def test_send_message(access_token, agent_id, user_id):
    """测试发送消息"""
    print(f"\n📤 测试发送消息...")
    
    try:
        url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}"
        
        payload = {
            "touser": user_id,
            "msgtype": "text",
            "agentid": agent_id,
            "text": {
                "content": "🔧 这是一条测试消息，用于验证API权限配置"
            }
        }
        
        print(f"   agentid: {agent_id}")
        print(f"   touser: {user_id}")
        
        response = requests.post(url, json=payload, timeout=10)
        result = response.json()
        
        if result.get('errcode') == 0:
            print(f"   ✅ 发送消息成功: {result}")
            return True
        elif result.get('errcode') == 301002:
            print(f"   ❌ 权限错误：当前access_token无权操作agentid {agent_id}")
            print(f"      请检查WX_AGENT_SECRET配置是否正确")
            return False
        else:
            print(f"   ❌ 发送消息失败: {result}")
            return False
            
    except Exception as e:
        print(f"   ❌ 发送消息异常: {str(e)}")
        return False

def main():
    """主函数"""
    print("🚀 企业微信配置检查工具")
    print("=" * 50)
    
    # 检查环境变量
    if not check_env_vars():
        print("\n❌ 请先配置必要的环境变量后再运行此脚本")
        return
    
    # 获取配置
    corp_id = os.getenv('WX_CORPID')
    corp_secret = os.getenv('WX_CORPSECRET')
    agent_secret = os.getenv('WX_AGENT_SECRET')
    agent_id = os.getenv('WX_AGENT_ID', '1000002')
    
    # 测试客服应用access_token
    kf_access_token = test_access_token(corp_id, corp_secret, "客服应用")
    
    # 测试内部消息应用access_token
    agent_access_token = test_access_token(corp_id, agent_secret, "内部消息应用")
    
    if agent_access_token:
        # 测试获取应用列表
        agent_list = test_agent_list(agent_access_token)
        
        # 测试发送消息（需要配置测试用户ID）
        test_user_id = os.getenv('WX_TEST_USER_ID')
        if test_user_id:
            test_send_message(agent_access_token, agent_id, test_user_id)
        else:
            print(f"\n⚠️  未配置WX_TEST_USER_ID，跳过消息发送测试")
            print(f"   如需测试消息发送，请配置WX_TEST_USER_ID环境变量")
    
    print("\n" + "=" * 50)
    print("📋 配置建议:")
    print("1. 确保WX_CORPSECRET是客服应用的Secret")
    print("2. 确保WX_AGENT_SECRET是内部消息应用的Secret")
    print("3. 确保WX_AGENT_ID是内部消息应用的AgentID")
    print("4. 确保内部消息应用有发送消息的权限")
    print("5. 如需测试消息发送，请配置WX_TEST_USER_ID")

if __name__ == '__main__':
    main() 